<template>
  <div>
    <el-row type="flex" class="row-bg" justify="center">
      <el-col :span="6"></el-col>
      <el-col :span="7">
        <!--logo区域-->
        <!--在页面直接使用组件svg-icon，其中incoClass命名等于svg文件的名称-->
        <div style="text-align: center">
          <svg-icon icon-class="cloudNoteN" style="width:200px; height: 130px"/>
        </div>
        <!--注册区域-->
        <el-card>
          <div class="title">
            <h1 style="border-bottom: 5px solid #2491f6;">注册云N记通行证</h1>
          </div>
          <div class="tip">
            <p>注册即代表同意遵守
              <a href="">《云N记通行证用户服务协议》</a>
              <a href="">《云N记通行证用户个人信息及隐私保护政策》</a>
            </p>
          </div>
          <el-form :model="userForm" status-icon :rules="userFormRules" ref="userFormRef" label-width="0px">
            <el-form-item prop="email">
              <el-input v-model="userForm.email" placeholder="邮箱" clearable></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input type="password" v-model="userForm.password" placeholder="密码" autocomplete="off"
                        clearable></el-input>
            </el-form-item>
            <el-form-item prop="password2">
              <el-input type="password" v-model="userForm.password2" placeholder="确认密码" autocomplete="off"
                        clearable></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <el-input class="verify" v-model="userForm.code" placeholder="邮箱验证码" clearable></el-input>
              <el-button type="primary" ref="codeInput" style="margin-left: 22px;" @click="send_sms_code()">
                {{ sms_code_tip }}
              </el-button>
            </el-form-item>
            <el-form-item style="display: flex;justify-content: center;">
              <el-checkbox v-model="checked" label="我是人类" border></el-checkbox>
              <i :class="[!verifySuccess?'el-icon-info':'el-icon-success','icon']"
                 :style="color?'color:#67c23a;':'color:#909399'"></i>
            </el-form-item>
            <el-form-item style="display: flex;justify-content: center;">
              <el-button class="btn" type="primary" @click="submitForm('ruleForm')">立即注册</el-button>
              <el-button class="btn" @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
          <div style="text-align: right">
            <el-link type="success" @click="$router.push('/page_of_login')" :underline="false">返回登录</el-link>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6"></el-col>
    </el-row>
    <el-dialog :visible.sync="slideVerifyDialogVisible" :show-close="false" width="450px">
      <slide-verify2 ref="slideVerify"
        :dialogVisible="slideVerifyDialogVisible"
        :verify="verifySuccess"
        @dialog="setSlideVerifyDialogVisible"
        @verified="setVerifySuccess"
      ></slide-verify2>
    </el-dialog>
  </div>
</template>

<script>
import slideVerify2 from '../components/login/slideVerify2'
import GetUUID from '../utils/uuid'

export default {
  data () {
    // 验证手机号/邮箱验证的规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      // const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regEmail.test(value)) {
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('请输入合法的邮箱'))
    }
    // 校验密码
    const checkpassword = (rule, value, callback) => {
      const regPassword1 = /^(?![a-zA-Z]+$)(?![0-9]+$)(?![._~!@#$^&*]+$)(?![0-9a-zA-Z]+$)(?![0-9._~!@#$^&*]+$)(?![a-zA-Z._~!@#$^&*]+$)[A-Za-z0-9._~!@#$^&*]{8,20}$/
      if (regPassword1.test(value)) {
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('1.密码必须由字母、数字、特殊符号组成，区分大小写\n' +
        '2.特殊符号包含（. _ ~ ! @ # $ ^ & *）\n' +
        '3.密码长度为8-20位'))
    }
    const checkpassword2 = (rule, value, callback) => {
      const regPassword2 = /^(?![a-zA-Z]+$)(?![0-9]+$)(?![._~!@#$^&*]+$)(?![0-9a-zA-Z]+$)(?![0-9._~!@#$^&*]+$)(?![a-zA-Z._~!@#$^&*]+$)[A-Za-z0-9._~!@#$^&*]{8,20}$/
      if (regPassword2.test(value)) {
        if (this.userForm.password === this.userForm.password2) return callback()
        else callback(new Error('两次密码不一样'))
      }
      // 返回一个错误提示
      callback(new Error('1.密码必须由字母、数字、特殊符号组成，区分大小写\n' +
        '2.特殊符号包含（. _ ~ ! @ # $ ^ & *）\n' +
        '3.密码长度为8-20位'))
    }
    return {
      userFormRules: {
        email: [{ required: true, message: '邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 6, max: 6, message: '验证码错误', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkpassword, trigger: 'blur' }],
        password2: [{ required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: checkpassword2, trigger: 'blur' }]
      },
      userForm: {
        uuid: '',
        email: '',
        code: '',
        password: '',
        password2: ''
      },
      sms_code_tip: '获取验证码',
      sending_flag: false,
      slideVerifyDialogVisible: false,
      verifySuccess: false,
      color: false,
      checked: false
    }
  },
  created () {
  },
  // DOM对象加载完成时
  mounted () {
  },
  methods: {
    // 提交表单
    submitForm () {
      this.$refs.userFormRef.validate((valid) => {
        if (valid && this.checkImgVerify() === true) {
          var url = this.$config.urls.get('register_auth')
          this.$http.post(url, this.userForm).then(res => {
            if (res.data.code !== 0) {
              this.$message.error(res.data.data.error_message)
            } else {
              var url2 = this.$config.urls.get('user_login')
              this.$http.post(url2, { email: this.userForm.email, password: this.userForm.password }).then(res => {
                if (res.data.code === 0) {
                  this.$memory.setToken(res.data.data.token)
                  this.$memory.setUserHeadImg(res.data.data.user.headimg)
                  this.$router.push({ name: 'index', params: res.data.data.user })
                  return this.$message.success('欢迎回来：' + res.data.data.user.nick)
                } else {
                  return this.$message.error('登录失败:' + res.data.error_message)
                }
              })
            }
          }).catch(e => {
            console.log(e)
          })
        } else {
          console.log('注册失败')
          return false
        }
      })
    },
    // 重置
    resetForm () {
      this.$refs.userFormRef.resetFields()
      this.verifySuccess = false
      this.color = false
      this.checked = false
      // console.log(this.$refs.slideVerify)
      this.$refs.slideVerify.handleClick()
    },
    // 发送短信验证码
    send_sms_code () {
      // 避免重复点击
      if (this.sending_flag === true) { // 先判断是否有人上厕所
        return// 有人则退出
      }
      this.sending_flag = true// 厕所无人，进入并关门
      // 校验参数
      // 验证码校验和邮箱
      if (this.checkImgVerify() === true && this.checkEmail() === true) {
        this.sending_flag = true
      } else {
        this.$message.error('请先进行图片验证！')
        this.sending_flag = false
        return
      }
      // 请求短信验证码
      this.userForm.uuid = GetUUID.generateUUID().replace(/-/g, '')
      var url = this.$config.urls.get('get_active_code')
      // console.log("发送短信验证码")
      this.$http.get(url, { params: { EMAIL: this.userForm.email, UUID: this.userForm.uuid } }).then(res => {
        console.log(res)
        if (res.data.code === 0) {
          // 倒计时60秒
          var num = 60
          var t = setInterval(() => {
            if (num === 1) {
              // 清除定时器，停止回调函数的执行
              clearInterval(t)
              // 更新sms_code_tip的提示信息
              this.sms_code_tip = '重新获取短'
              // 重新生成图形验证码
              this.$refs.slideVerify.onFulfilled()
              this.sending_flag = false
            } else {
              num -= 1
              // 展示倒计时信息
              this.sms_code_tip = num + '秒'
            }
          }, 1000, 60)
        } else {
          // 不成功
          if (res.data.code !== 0) {
            this.$message.error(res.data.data.error_message)
            console.log(res.data.data.error_message)
          }
          this.$refs.slideVerify.onFulfilled()
          this.sending_flag = false
        }
      })
        .catch(error => {
          console.log(error.response)
          this.sending_flag = false
        })
    },
    // 设置滑动验证是否显示
    setSlideVerifyDialogVisible (value) {
      this.slideVerifyDialogVisible = value
    },
    // 设置是否验证成功
    setVerifySuccess (value) {
      this.verifySuccess = value
    },
    // 验证码校验
    checkImgVerify () {
      return this.verifySuccess
    },
    // 邮箱校验
    checkEmail () {
      return !(this.userForm.email === '' || this.userForm.email === null)
    }
  },
  components: { slideVerify2 },
  watch: {
    // 监听verifySuccess的值，如果改变，color值也变
    verifySuccess: {
      handler (oldVal, newVal) {
        this.color = !(oldVal === false && newVal === true)
      },
      deep: true,
      immediate: false
    },
    // 监听checked的值，如果改变，slideVerifyDialogVisible,verifySuccess也变
    checked: {
      handler (oldVal, newVal) {
        if (oldVal === false && newVal === true) {
          // console.log(this.checked)
          // console.log(this.slideVerifyDialogVisible)
          this.slideVerifyDialogVisible = false
          this.verifySuccess = false
          this.$refs.slideVerify.handleClick()
        } else {
          // console.log(this.checked)
          // console.log(this.slideVerifyDialogVisible)
          this.slideVerifyDialogVisible = true
          this.verifySuccess = true
        }
      },
      deep: true,
      immediate: false
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  padding: 20px 60px
}

.el-input, .btn {
  margin-top: 15px;
}

.verify {
  width: 60%;
}

.title {
  text-align: center;
  color: #2491f6;
}

.tip {
  font-size: 12px;

  a {
    color: #2491f6;
  }
}

.icon {
  font-size: 40px;
  vertical-align: middle
}
</style>
